const mongoose = require('mongoose');

// 定义Post Schema
const postSchema = new mongoose.Schema({
  _id: {
    type: Number,
    required: true
  },
  title: {
    type: String,
    required: [true, '标题是必需的'],
    trim: true
  },
  content: {
    type: String,
    required: [true, '内容是必需的']
  },
  author: {
    type: String,
    required: [true, '作者是必需的'],
    trim: true
  },
  categoryId: {
    type: Number,
    default: null
  },
  createdAt: {
    type: Date,
    default: Date.now
  },
  updatedAt: {
    type: Date,
    default: Date.now
  }
});

// 添加更新时间的中间件
postSchema.pre('save', function (next) {
  if (this.isModified()) {
    this.updatedAt = Date.now();
  }
  next();
});

// 更新文章的方法
postSchema.methods.updatePost = function (title, content, categoryId = null) {
  this.title = title;
  this.content = content;
  this.categoryId = categoryId;
  this.updatedAt = Date.now();
  return this.save();
};

// 静态验证方法
postSchema.statics.validatePost = function (postData) {
  const errors = [];
  
  if (!postData.title || postData.title.trim() === '') {
    errors.push('标题是必需的');
  }
  
  if (!postData.content || postData.content.trim() === '') {
    errors.push('内容是必需的');
  }
  
  if (!postData.author || postData.author.trim() === '') {
    errors.push('作者是必需的');
  }
  
  return {
    valid: errors.length === 0,
    errors
  };
};

// 创建Post模型
const Post = mongoose.model('Post', postSchema);

// 初始文章数据
const posts = [
  { 
    id: 1, 
    title: '欢迎使用博客系统', 
    content: '这是我们的第一个博客文章，介绍了系统的基本功能。', 
    author: '管理员', 
    categoryId: 1,
    createdAt: new Date(),
    updatedAt: new Date()
  },
  { 
    id: 2, 
    title: 'Node.js 开发技巧', 
    content: '在这篇文章中，我们将分享一些 Node.js 开发的实用技巧和最佳实践。', 
    author: '张三', 
    categoryId: 1,
    createdAt: new Date(),
    updatedAt: new Date()
  },
  { 
    id: 3, 
    title: 'Vue.js 组件设计', 
    content: '探讨如何设计可复用和可维护的 Vue.js 组件。', 
    author: '李四', 
    categoryId: 1,
    createdAt: new Date(),
    updatedAt: new Date()
  }
];

module.exports = {
  Post,
  posts
};